package com.study.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.common.utils.PageUtils;
import com.study.common.utils.Query;

import com.study.product.dao.CategoryDao;
import com.study.product.entity.CategoryEntity;
import com.study.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listCategoryWithTree() {
        //查询出所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //过滤出树形结构的多级分类
        return entities.stream().filter(categoryEntity ->
                //找出菜单的第一级父分类
                categoryEntity.getParentCid() == 0
        ).map(parentMenu -> {
            //递归查询出所有子分类，然后将这些子分类存放在夫分类的childCateList中
            parentMenu.setChildrenCategory(this.getChildrenCatetgories(parentMenu, entities));
            return parentMenu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public void delCateNodeByIds(List<Long> catIds) {
        //TODO 逻辑删除并且删除之前需要考虑其他地方是否用得到该数据
        baseMapper.deleteBatchIds(catIds);
    }

    /**
     * 获取菜单的子分类
     * @param menuSorce
     * @param entities
     * @return
     */
    private List<CategoryEntity> getChildrenCatetgories(CategoryEntity menuSorce, List<CategoryEntity> entities) {
        return entities.stream().filter(categoryEntity ->
                //通过拿到的上一级的夫分类id，去查找对应的子分类的分类id
                categoryEntity.getParentCid().equals(menuSorce.getCatId())
        ).map(parentMenu -> {
            //递归查询出所有子分类，然后将这些子分类存放在夫分类的childCateList中
            parentMenu.setChildrenCategory(this.getChildrenCatetgories(parentMenu, entities));
            return parentMenu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

}